﻿using Microsoft.AspNetCore.Mvc;
using PetaPoco;
using Qy.Common;
using Qy.Models;
using Qy.Service;
using Qy.Web.Authorize;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Web.Api
{
    [Route("Api/[controller]/[action]")]
    [Verify]
    public class UserController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly UserService _adminUserService;
        private readonly UserGroupService _adminUserGroupService;
        private readonly UserDeptService _adminUserDeptService;
        private readonly UserPostService _adminUserPostService;
        public UserController(
            LoginUtil LoginUtil,
            UserService adminUserService,
            UserGroupService adminUserGroupService,
            UserDeptService adminUserDeptService,
            UserPostService adminUserPostService
            )
        {
            _LoginUtil = LoginUtil;
            _adminUserService = adminUserService;
            _adminUserGroupService = adminUserGroupService;
            _adminUserDeptService = adminUserDeptService;
            _adminUserPostService = adminUserPostService;
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.User_Index)]
        public async Task<IActionResult> ListAsync([FromQuery] UserQuery query)
        {
            int gid = _LoginUtil.LoginGroupId();//判断普通用户不能看超级管理员
            Page<ViewUser> list = await _adminUserService.GetPageListAsync(query, gid);
            return Json(new { status = 1, data = list.Items, count = list.TotalItems });

        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.UserDept_Index)]
        public async Task<IActionResult> DeptListTreeAsync()
        {
            var pagedList = await _adminUserDeptService.AsUserDeptTree();
            return Json(new { status = 1, data = pagedList });
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEditView)]
        public async Task<IActionResult> AddOrEditAsync(int id)
        {
            int gid = _LoginUtil.LoginGroupId();

            List<UserGroup> userGroups = await _adminUserGroupService.GetListAsync();
            if (gid != 1)
                userGroups.RemoveAll(e => e.Id == 1);//只有超级管理员才能添加超级管理员用户

            var userDepts = await _adminUserDeptService.GetUserDeptListAsync();
            var userPosts = await _adminUserPostService.GetAllAsync();

            if (id > 0)
            {
                User user = await _adminUserService.GetNoCacheAsync(id);
                user.Password = null;
                return Json(new { status = 1, data = user, userGroups, userDepts, userPosts });
            }

            return Json(new { status = 1, userGroups, userDepts, userPosts });

        }
        [HttpGet]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_UserChange)]
        public async Task<IActionResult> UserChangeAsync()
        {
            ViewUser user = await _adminUserService.GetAsync(_LoginUtil.LoginUserId());
            return Json(new { status = 1, data = user });
        }

        [HttpPut]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_UserChangeEdit)]
        [Log(Name = "修改个人信息")]
        public async Task<IActionResult> UserChangePostAsync([FromBody] EditUser editUser)
        {
            if (ModelState.IsValid)
            {
                int userId = _LoginUtil.LoginUserId();

                if (1 > await _adminUserService.EditUserInfoUpdateAsync(editUser, userId))
                    return Json(new { status = 0, msg = "修改失败，有可能是旧密码不正确！" });
                return Json(new { status = 1, msg = "修改个人信息:" + editUser.Username + " - " + editUser.Nickname });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        [HttpPost, ActionName("Create")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
        [Log(Name = "新增用户")]
        public async Task<IActionResult> CreatePostAsync([FromBody] EditUser user)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(user.Password))
                    return Json(new { status = 0, msg = "新增用户密码不能为空！" });

                if (await _adminUserService.GetByUsernameAsync(user.Username) == false)
                    return Json(new { status = 0, msg = "该登录名已存在，请重新输入！" });

                User adminUser = new()
                {
                    Gid = user.Gid,
                    DeptId = user.DeptId,
                    PostId = user.PostId,
                    Username = user.Username,
                    Password = MD5Utility.MD5Encrypt32(user.Password).ToLower(),
                    Nickname = user.Nickname,
                    Status = user.Status
                };
                var res = await _adminUserService.InsertAsync(adminUser);
                return Json(new { status = 1, msg = "添加成功 Id:" + res.ToString() });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        [HttpPut, ActionName("Edit")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
        [Log(Name = "修改用户")]
        public async Task<IActionResult> EditPost([FromBody] EditUser user)
        {
            if (ModelState.IsValid)
            {
                int res = await _adminUserService.UpdateAsync(user);
                return res switch
                {
                    0 => Json(new { status = 0, msg = "编辑失败 Id:" + user.Id + "可能是写入数据库错误" }),
                    -1 => Json(new { status = 0, msg = "请勿非法提交 Id:" + user.Id }),
                    -2 => Json(new { status = 0, msg = "该用户名已存在，请重新输入 Id:" + user.Id }),
                    _ => Json(new { status = 1, msg = "成功编辑用户 Id:" + user.Id }),
                };
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }
        [HttpPut, ActionName("ChStatus")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
        [Log(Name = "修改用户状态")]
        public async Task<IActionResult> ChStatus([FromBody] EditUserStatus adminUser)
        {
            if (ModelState.IsValid)
            {
                if (0 < await _adminUserService.ChStatusUpdateAsync(adminUser))
                    return Json(new { status = 1, msg = "设置为 " + adminUser.Status.ToString() + ", Id:" + adminUser.Id });
                else
                    return Json(new { status = 0, msg = "设置为 " + adminUser.Status.ToString() + ", Id:" + adminUser.Id });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }
        [HttpDelete]
        [ActionPermissionFilter(Permission = PermissionKeys.User_Delete)]
        [Log(Name = "删除用户")]
        public async Task<IActionResult> Delete(int id)
        {
            if (await _adminUserService.DeleteByPriKeyAsync(id) > 0)
            {
                return Json(new { status = 1, msg = "删除用户 id:" + id });
            }
            else
                return Json(new { status = 0, msg = "删除失败！" });
        }

    }
}
